package com.ljp.makefriend.job;

import com.ljp.makefriend.WebSocket.ChatEndPoint;
import com.ljp.makefriend.pojo.ChatMessages;
import com.ljp.makefriend.service.ChatMessagesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 缓存中消息持久化
 * @author 沐风
 */
@Slf4j
@Component
public class MessageCacheEndurance {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private ChatMessagesService chatMessagesService;

    // 每天的凌晨3点执行消息持久化
    @Scheduled(cron = "0 0 3 * * ? ")  // cron 表达式 TODO 更换 cron 表达式
    public void doMessageCacheEndurance() {
        log.info("开始持久化用户聊天消息");
        // 1、获取用户聊天信息存储的 key
        HashSet<String> chatUserKeys = ChatEndPoint.chatUserKeys;
        for (String chatUserKey: chatUserKeys) {
            // 2、通过key获取redis中对应用户的聊天信息
            Set<String> messageKeys = redisTemplate.opsForList().getOperations().keys(chatUserKey);
            // 3、判断参数
            if (messageKeys == null || messageKeys.isEmpty()) {
                return;
            }
            // 获取每一个 key
            String messageKey = null;
            for (String key: messageKeys) {
                messageKey = key;
            }

            Long size = redisTemplate.opsForList().size(messageKey);
            if (size == null || size <= 0) {
                continue;
            }

            List<Object> resultMessages = redisTemplate.opsForList().range(messageKey, 0, size);
            if (resultMessages == null || resultMessages.isEmpty()) {
                continue;
            }
            List<ChatMessages> chatMessagesList = new ArrayList<>();
            for (Object resultMessage: resultMessages) {
                ChatMessages chatMessage = new ChatMessages();
                BeanUtils.copyProperties(resultMessage, chatMessage);
                chatMessagesList.add(chatMessage);
            }
            // 4、将聊天信息存入数据库
            boolean result = chatMessagesService.saveBatch(chatMessagesList);
            // 5、删除 redis 中的缓存数据和用户的 key
            if (result) {
                redisTemplate.delete(messageKey);
            }
        }
        // 清空用户聊天 key
        ChatEndPoint.chatUserKeys.clear();
        log.info("持久化用户聊天消息完成");
    }




}
